package globalTools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import appModel.GridsCollection;

public abstract class Savable implements Serializable {

	// ATTRIBUTS
	
	private static final long serialVersionUID = 1L;
	
	private String file;
	
	// CONSTRUCTEUR
	
	protected Savable(String filePath) {
		if (filePath == null) {
			throw new IllegalArgumentException();
		}
		file = filePath;
	}
	
	// REQUETES
	
	public static Object getSaved(String f) throws IOException {
		Object res = null;
		FileInputStream fis;
		try {
			fis = new FileInputStream(new File(f));
			ObjectInputStream ois = new ObjectInputStream(fis);
			res = ois.readObject();
			ois.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public static Object getSaved(String f, Object o) {
		try {
			InputStream is = o.getClass().getResourceAsStream(f);
			if (is == null) {
				return null;
			}
			ObjectInputStream ois = new ObjectInputStream(is);
			return (GridsCollection) ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// COMMANDES
	
	protected void save() throws IOException {
		FileOutputStream fos;
		fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        try {
        	oos.writeObject(this);
        	oos.flush();
        } finally {
        	try {
        		oos.close();
        	} finally {
        		fos.close();
        	}
        }
	}

}
